import _axios from '../../../_utils/http/_axios'

import { NET_ERRORNET_ERROR } from '../../consts/httpCode'

import { interceptor } from '../../../_utils/http/interceptors'

//  1.  创建axios实例对象


_axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

    /**
     * 发送网络请求
     * @param {*} url 
     * @param {*} params 
     * @param {*} config 
     * @param {*} method 
     * @returns 
     */
    const request = function (url, params, config, method) {
            return _axios[method](url, params, Object.assign({}, config))
                .then(checkStatus).then(checkCode);
    };

    /**
     * 检查网络校验
     * @param {*} response 
     */
    const checkStatus = response=> {
            // 如果 http 状态码正常, 则直接返回数据
        if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response.data || NET_ERRORNET_ERROR
        }
        return NET_ERRORNET_ERROR

    }
    /**
     * 统一返回数据
     * @param {*} res 
     * @returns 
     */
    const checkCode = (res) => {
        return res;
    }

    const interceptors = ()=>{
        return _axios.interceptors
    }
// 暴露接口

export default {
    /**
     * axios的初始化
     * @param {*} option 
     */
    init: (option = {withCredentials: true})=> {
        _axios.defaults.baseURL = option.url;
        _axios.defaults.timeout = option.timeout || 3000;
        _axios.defaults.withCredentials = option.withCredentials;
    },
    /**
     * 是否开启拦截器与自定义拦截器
     * @param {*} flag 
     * @returns 
     */
    isInterceptor: (flag = true) => { 
        interceptor(!flag) 
        if(flag === false) {
            return  interceptors();
        }
    },
    /**
     * Get方法
     * @param {*} url 
     * @param {*} params 
     * @param {*} config 
     * @returns 
     */
    Get: (url,params, config = {}) => request(url, params, config, 'get'),
    
    /* Post方法
     * @param {*} url 
     * @param {*} params 
     * @param {*} config 
     * @returns 
     */
    Post: (url,params, config = {}) => request(url, params, config, 'post'),
    
    /**
     * Delete方法
     * @param {*} url 
     * @param {*} params 
     * @param {*} config 
     * @returns 
     */
    Delete: (url,params, config = {}) => request(url, params, config, 'delete'),

    /**
     * Put 方法
     * @param {*} url 
     * @param {*} params 
     * @param {*} config 
     * @returns 
     */
    Put: (url,params, config = {}) => request(url, params, config, 'put'),

}


